<template>
  <ul class="tree-root" v-if="trees.length">
    <li class="item" v-for="(item, index) in trees" :key="index" :data-level="item.level">
      <div :class="['content', {isActive: item.isActive}]" :style="{paddingLeft: item.level * 20 + 'px'}">
        <span><i class="icon"></i>{{item.name}}</span>
      </div>
      <tree v-if="item.children && item.children" :datas="item.children"/>
    </li>
  </ul>
</template>

<script>
export default {
  name: 'Tree',
  props: {
    datas: {
      type: Array,
      default: () => ([
        {
          name: '一级',
          isActive: true, // 是否选中
          level: 0, // 表示层级
          children: [
            {
              name: '二级',
              level: 1
            },
            {
              name: '二级',
              level: 1
            }
          ]
        }, 
        {
          name: '一级',
          level: 0,
          children: [
            {
              name: '二级',
              level: 1,
              children: [
                {
                  name: '三级',
                  level: 2
                }
              ]
            },
            {
              name: '二级',
              level: 1
            }
          ]
        }
      ])
    }
  },
  data () {
    return {
      trees: null
    }
  },
  created () {
    this.trees = JSON.parse(JSON.stringify(this.datas));
    this.addMenuLevel(this.trees);
  },
  methods: {
    addMenuLevel (data, curLevel = -1) {
      for (let i = 0, len = data.length; i < len; i++) {
        const temp = 1;
        if (data[i].children && !data[i].level) {
          data[i].level = temp + curLevel;
          this.addMenuLevel(data[i].children, data[i].level);
        }
      }
    } 
  }
}
</script>

<style lang="less" scoped>
.tree-wrapper * {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
ul.tree-root {
  list-style: none;
  text-align: left;
  line-height: 26px;
  li.item {
    .content {
      border-bottom: 1px solid #ccc;
      &:hover {
        color: blue;
        background: #ccc;
      }
    }
    .isActive {
      color: red;
    }
  }
}

</style>
